import { Next, Context } from 'koa';
import { UserService } from '@/services/user';
import { UserRoles } from '@/enums/userEnums';
import { NoPermissionErrors, ResponseErrors } from '@/enums/responseErrors';

/**
 * 统一获取user信息
*/
export const userMiddleware = async (ctx: Context, next: Next) => {
  const uid = ctx.userId;
  if (uid) {
    const user = await UserService.findUserByIdAndOmitPassword(uid);
    if (!user) {
      ctx.sendError(ResponseErrors.userNotExist);
      return;
    };
    // 在后台管理系统需要管理员权限才能请求接口
    if (ctx.platform === 'adminSystem') {
      if (user.role !== UserRoles.admin) {
        ctx.sendError(NoPermissionErrors.userNoPermission);
        return;
      }
    }
    ctx.user = user;
  }
  await next();
}